<template>
  <div class="page-container">
    <div class="cart-container">
      <a-page-header title="My shopping cart" sub-title="Manage your shopping cart merchandise"/>

      <div v-if="cartItems.length === 0 && !loading" class="empty-state">
        <a-result
            status="info"
            title="Your shopping cart is empty"
            sub-title="Add items to your cart to start shopping"
        >
          <template #extra>
            <a-button type="primary" @click="goToProducts">
              <shopping-outlined /> Go shopping
            </a-button>
          </template>
        </a-result>
      </div>

      <!-- 购物车列表加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-content">
          <a-spin />
          <div class="loading-text">You have no favorite products</div>
          <a-button type="primary" class="loading-button">Go Shopping</a-button>
        </div>
      </div>

      <template v-if="cartItems.length > 0 && !loading">
        <a-card class="cart-card">
          <a-table
              :dataSource="cartItems"
              :columns="columns"
              :pagination="pagination"
              :rowKey="record => record.id"
              class="cart-table"
              @change="handleTableChange"
          >
            <!-- 选择框列 -->
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'select'">
                <a-checkbox
                    v-model:checked="record.selected"
                    @change="updateSelection"
                />
              </template>

              <!-- 商品列 -->
              <template v-if="column.key === 'product'">
                <div class="product-cell">
                  <img :src="record.image" :alt="record.name" class="product-image"/>
                  <div class="product-info">
                    <div class="product-name">{{ record.name }}</div>
                    <div class="product-specs">
                      <template v-if="parseSpecText(record.specs).imageUrl">
                        <div class="color-image-container">
                          <img :src="parseSpecText(record.specs).imageUrl" :alt="record.name" class="color-image"/>
                        </div>
                      </template>
                      <span>{{ parseSpecText(record.specs).size }}</span>
                    </div>
                  </div>
                </div>
              </template>

              <!-- 单价列 -->
              <template v-if="column.key === 'price'">
                <span class="price">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(record.price, false, false) }}</span>
              </template>

              <!-- 数量列 -->
              <template v-if="column.key === 'quantity'">
                <a-input-number
                    v-model:value="record.quantity"
                    :min="1"
                    :max="record.stock"
                    @change="(value) => handleQuantityChange(record, value)"
                />
              </template>

              <!-- 小计列 -->
              <template v-if="column.key === 'subtotal'">
                <span class="subtotal">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice((record.price * record.quantity), false, false) }}</span>
              </template>

              <!-- 操作列 -->
              <template v-if="column.key === 'action'">
                <a-button type="link" @click="removeItem(record)" style="color: #000;">
                  <template #icon>
                    <DeleteOutlined :style="{ fontSize: '18px' }" />
                  </template>
                  delete
                </a-button>
              </template>
            </template>
          </a-table>

          <!-- 购物车底部结算栏 -->
          <div class="cart-footer">
            <div class="cart-footer-left">
              <a-checkbox
                  :checked="allSelected"
                  :indeterminate="indeterminate"
                  @change="toggleSelectAll"
              >
                Select all
              </a-checkbox>
              <a-button type="link" @click="handleClearCart">Clear the shopping cart</a-button>
            </div>

            <div class="cart-footer-right">
              <div class="cart-summary">
                <span><span class="highlight">{{ selectedCount }}</span> {{ selectedCount === 1 ? 'item' : 'items' }} selected</span>
                <span class="total-price">Total: <span class="highlight">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(totalPrice, false, false) }}</span></span>
              </div>
              <a-button
                  type="primary"
                  size="large"
                  :disabled="!hasSelectedItems"
                  @click="checkout"
              >
                checkout
              </a-button>
            </div>
          </div>
        </a-card>
      </template>

      <!-- 相关推荐 -->
      <div class="recommendations">
        <h3>Customers Also Bought</h3>

        <div v-if="recommendLoading" class="recommendation-loading">
          <a-row :gutter="[16, 16]" class="recommendations-grid">
            <a-col :xs="24" :sm="12" :md="8" :lg="4" v-for="item in 6" :key="item">
              <a-card class="recommendation-card skeleton-card">
                <template #cover>
                  <div class="recommendation-image-skeleton"></div>
                </template>
                <div class="recommendation-meta-skeleton">
                  <div class="title-skeleton"></div>
                  <div class="price-skeleton"></div>
                </div>
                <div class="rec-action-skeleton"></div>
              </a-card>
            </a-col>
          </a-row>
        </div>

        <a-row v-else :gutter="[16, 16]" class="recommendations-grid">
          <a-col :xs="24" :sm="12" :md="8" :lg="4" v-for="item in recommendedItems" :key="item.id">
            <a-card hoverable @click="addToCart(item)" class="recommendation-card">
              <template #cover>
                <img :src="item.images[0]" :alt="item.name" class="recommendation-image"/>
              </template>
              <a-card-meta :title="item.name">
                <template #description>
                  <div class="rec-price">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(item.min_price, false, false) }}</div>
                </template>
              </a-card-meta>
              <div class="rec-action">
                <a-button type="primary" block @click.stop="addToCart(item)">Quick View</a-button>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>

  <!-- Add modal for product detail -->
  <a-modal v-model:open="open" width="1260px" title="Product Detail" :footer="null">
    <ProductDetail.default v-if="open && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script setup>
import { ref, computed, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import { DeleteOutlined, ShoppingOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { useCurrencyStore, useCommonStore } from '@/store';
import { getCartList, editCartNum, deleteCartItem, clearCart as clearCartApi, cartOrder } from '@/api/user';
import {hotGoodsList} from "@/api/goods.ts";
import {addCarts} from "@/api/goods.ts";
import * as ProductDetail from '@/components/ProductDetail.vue';
import { addToBrowsingHistory } from '@/utils/cache';
import { CartAdapter } from '@/utils/cache';

const router = useRouter();
const { proxy } = getCurrentInstance();
const useCurrency = useCurrencyStore();

// 表格列定义
const columns = [
  {
    title: '',
    key: 'select',
    width: 60
  },
  {
    title: 'product',
    key: 'product',
    width: 400
  },
  {
    title: 'price',
    key: 'price',
    width: 120
  },
  {
    title: 'quantity',
    key: 'quantity',
    width: 120
  },
  {
    title: 'subtotal',
    key: 'subtotal',
    width: 120
  },
  {
    title: 'action',
    key: 'action',
    width: 100
  }
];

// 购物车数据
const cartItems = ref([]);

// 分页相关状态
const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `${total} entries in total`,
  pageSizeOptions: ['15', '30', '50', '100']
});

// 加载状态
const loading = ref(false);
const recommendLoading = ref(false);
// 防止重复提交的标志位
const isSubmitting = ref(false);

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 获取购物车列表
const fetchCartList = async () => {
  loading.value = true;
  try {
    const res = await getCartList({
      page: pagination.current,
      page_size: pagination.pageSize
    });

    if (res.code === 200) {
      const cartItemsData = res.result.data.map(item => ({
        id: item.id,
        name: item.goods.name,
        specs: item.sku.spec_text,
        price: parseFloat(item.sku.price),
        quantity: item.num,
        stock: item.sku.stock,
        selected: item.selected === 1,
        image: item.sku.image,
        goods_id: item.goods_id,
        sku_id: item.sku_id
      }));
      
      // 使用CartAdapter保存购物车数据
      CartAdapter.saveCartItems(cartItemsData);
      
      // 更新组件内的购物车数据
      cartItems.value = cartItemsData;
      pagination.total = res.result.total;
      pagination.current = res.result.current_page;
    } else {
      message.error(res.msg || 'Failed to get the shopping cart list');
      
      // 如果API失败，尝试从缓存获取数据
      const cachedCartItems = CartAdapter.getCartItems();
      if (cachedCartItems && cachedCartItems.length > 0) {
        cartItems.value = cachedCartItems;
        message.info('Displaying cached cart data');
      }
    }
  } catch (error) {
    message.error('Failed to get the shopping cart list, please try again later');
    
    // 如果API请求出错，尝试从缓存获取数据
    const cachedCartItems = CartAdapter.getCartItems();
    if (cachedCartItems && cachedCartItems.length > 0) {
      cartItems.value = cachedCartItems;
      message.info('Displaying cached cart data');
    }
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchCartList();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCartList();
  getHotGoodsList();
});

// 猜你喜欢商品
const recommendedItems = ref([]);
// 获取热度商品列表
const getHotGoodsList = async () => {
  recommendLoading.value = true;
  try {
    const res = await hotGoodsList();
    if (res.code == 200) {
      recommendedItems.value = res.data[0].list;
    }
  } catch (error) {
    console.error('Failed to obtain recommended products:', error);
    message.error('Failed to obtain recommended products, please try again later');
  } finally {
    recommendLoading.value = false;
  }
}

// 计算属性
// 是否全选
const allSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
});

// 是否部分选中
const indeterminate = computed(() => {
  return cartItems.value.some(item => item.selected) && !allSelected.value;
});

// 已选择的商品
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected);
});

// 已选择的商品数量
const selectedCount = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.quantity, 0);
});

// 是否有选中的商品
const hasSelectedItems = computed(() => {
  return selectedItems.value.length > 0;
});

// 总价
const totalPrice = computed(() => {
  try {
    const total = selectedItems.value
        .filter(item => item && item.price && item.quantity)
        .reduce((sum, item) => {
          const price = Number(item.price) || 0;
          const quantity = Number(item.quantity) || 0;
          return sum + (price * quantity);
        }, 0);

    return total;
  } catch (error) {
    console.error('An error occurred in calculating the total price:', error);
    return 0;
  }
});

// 切换全选
const toggleSelectAll = (e) => {
  const checked = e.target.checked;
  cartItems.value.forEach(item => {
    item.selected = checked;
  });
  
  // 更新购物车缓存
  CartAdapter.saveCartItems(cartItems.value);
};

// 更新选择状态
const updateSelection = () => {
  // 复选框状态改变时，Vue的响应式系统会自动更新UI
  // 不需要额外操作，因为allSelected、indeterminate、selectedItems等计算属性会自动重新计算
  
  // 更新购物车缓存
  CartAdapter.saveCartItems(cartItems.value);
};

// 更新购物车项
const updateItemAction = async (item, oldQuantity) => {
  if (isSubmitting.value) return;

  isSubmitting.value = true;
  try {
    const res = await editCartNum({
      id: item.id,
      num: item.quantity
    });

    if (res.code === 200) {
      message.success(`The number of "${item.name}" updated is ${item.quantity}`);
      // 不刷新整个购物车，只更新当前商品数量
      // 重新计算小计和总价会自动更新，因为它们是响应式计算属性
    } else {
      message.error(res.msg || 'Update number failed');
      // 恢复原来的数量
      item.quantity = oldQuantity;
    }
  } catch (error) {
    message.error('The number of updates failed, please try again later');
    // 恢复原来的数量
    item.quantity = oldQuantity;
  } finally {
    isSubmitting.value = false;
  }
};

// 使用防抖函数包装更新操作
const updateItem = debounce((item, oldQuantity) => {
  updateItemAction(item, oldQuantity)
    .then(() => {
      // 更新成功后更新缓存
      CartAdapter.saveCartItems(cartItems.value);
    })
    .catch(() => {
      // 出错处理已在updateItemAction内部完成
    });
}, 500);

// 从购物车移除
const removeItem = (item) => {
  Modal.confirm({
    title: 'Confirm deletion',
    content: `Are you sure you want to remove "${item.name}" from your cart?`,
    okText: 'confirm',
    cancelText: 'cancel',
    onOk: async () => {
      try {
        const res = await deleteCartItem({ id: item.id });
        if (res.code === 200) {
          message.success(`Removed from cart "${item.name}"`);
          // 本地移除商品，不刷新整个列表
          const index = cartItems.value.findIndex(cartItem => cartItem.id === item.id);
          if (index > -1) {
            cartItems.value.splice(index, 1);
            // 更新缓存
            CartAdapter.saveCartItems(cartItems.value);
          }
        } else {
          message.error(res.msg || 'Deletion failed');
        }
      } catch (error) {
        message.error('Deletion failed, please try again later');
      }
    }
  });
};

// 清空购物车
const handleClearCart = () => {
  if (cartItems.value.length === 0) return;

  Modal.confirm({
    title: 'Clear the shopping cart',
    content: 'Are you sure you want to clear all items in your shopping cart？',
    okText: 'confirm',
    cancelText: 'cancel',
    onOk: async () => {
      try {
        const res = await clearCartApi();
        if (res.code === 200) {
          message.success('Shopping cart has been cleared');
          // 本地清空购物车，不刷新整个列表
          cartItems.value = [];
          // 清空缓存
          CartAdapter.clearCart();
        } else {
          message.error(res.msg || 'Failed to clear the cart');
        }
      } catch (error) {
        message.error('Failed to clear the shopping cart, please try again later');
      }
    }
  });
};

// 结算
const checkout = () => {
  if (!hasSelectedItems.value) return;
  // 将选中的商品转换为可序列化的对象数组
  const selectedItemsArray = selectedItems.value.map(item => ({
    id: item.id,
    name: item.name,
    specs: item.specs,
    price: Number(item.price),
    quantity: Number(item.quantity),
    image: item.image,
    goods_id: item.goods_id,
    sku_id: item.sku_id,
  }));

  // 使用购物车适配器存储选中的商品数据
  try {
    CartAdapter.saveCheckoutItems(selectedItemsArray);

    // 跳转到结算页面，只传递时间戳避免缓存问题
    router.push({
      path: '/user/checkout',
      query: {
        timestamp: new Date().getTime()
      }
    });
  } catch (error) {
    console.error('Failed to store product data:', error);
    message.error('Settlement failed, please try again later');
  }
};

// Add these new refs for the modal
const open = ref(false);
const goodId = ref(null);

// 添加到购物车
const addToCart = (item) => {
  try {
    open.value = true;
    goodId.value = String(item.goods_id || item.id);
    // 在商品详情组件中会自动添加浏览记录，所以这里不需要重复添加
  } catch (error) {
    console.error('Failed to open quick view:', error);
    message.error('Failed to open quick view, please try again later');
  }
};

// Add these new functions for the modal
const handleOk = () => {
  open.value = false;
  goodId.value = null;
};

const handleBuy = (data) => {
  if (!data) return;
  
  // message.success(`Product has been added to your cart.`);
  open.value = false;
  goodId.value = null;
  // After successfully adding to cart, refresh the cart list
  fetchCartList();
};

// 前往商品页面
const goToProducts = () => {
  router.push('/products');
};

// 解析规格文本
const parseSpecText = (specText) => {
  if (!specText) return { size: '', imageUrl: '' };

  // 检查是否包含图片URL和尺寸
  if (specText.includes('http') && specText.includes('，')) {
    const parts = specText.split('，');
    return {
      imageUrl: parts[0],
      size: parts[1] || ''
    };
  }

  // 检查是否只有图片URL
  if (specText.includes('http')) {
    return {
      imageUrl: specText,
      size: ''
    };
  }

  // 只有尺寸
  return {
    imageUrl: '',
    size: specText
  };
};

// 处理数量变化
const handleQuantityChange = (item, value) => {
  const oldQuantity = item.quantity;
  item.quantity = value;
  updateItem(item, oldQuantity);
};
</script>

<style scoped>
.page-container {
  padding: 0;
}

.cart-container {
  background: #fff;
}

.cart-card {
  border: 1px solid #000;
  border-radius: 4px;
  margin-top: 16px;

  :deep(.ant-card-body) {
    padding: 0;
  }
}

.cart-table {
  :deep(.ant-table) {
    background: transparent;
  }

  :deep(.ant-table-thead > tr > th) {
    background: #000;
    color: #fff;
    border-bottom: none;

    &::before {
      display: none;
    }
  }

  :deep(.ant-table-tbody > tr > td) {
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background: #f5f5f5;
  }
}

.product-cell {
  display: flex;
  align-items: center;
  gap: 16px;

  .product-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border: 1px solid #eee;
  }

  .product-info {
    flex: 1;

    .product-name {
      font-weight: 500;
      margin-bottom: 8px;
    }

    .product-specs {
      color: #666;
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 8px;

      .color-image-container {
        width: 20px;
        height: 20px;
        border: 1px solid #eee;
        border-radius: 2px;
        overflow: hidden;

        .color-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }
}

.price, .subtotal {
  font-weight: 500;
  color: #000;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;

  .cart-footer-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .cart-footer-right {
    display: flex;
    align-items: center;
    gap: 24px;

    .cart-summary {
      text-align: right;

      .highlight {
        color: #000;
        font-weight: bold;
        margin: 0 4px;
      }

      .total-price {
        margin-left: 16px;

        .highlight {
          font-size: 20px;
        }
      }
    }
  }
}

.recommendations {
  margin-top: 32px;

  h3 {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 16px;
    color: #000;
  }
}

.recommendation-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .recommendation-image {
    height: 240px;
    object-fit: cover;
    border-radius: 8px 8px 0 0;
  }

  :deep(.ant-card-meta) {
    margin: 12px 0;

    .ant-card-meta-title {
      font-size: 14px;
      color: #333;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .rec-price {
    font-size: 16px;
    font-weight: 500;
    color: #000;
  }

  .rec-action {
    margin-top: 12px;

    .ant-btn {
      height: 32px;
      font-size: 13px;
    }
  }
}

.empty-state {
  padding: 48px 0;
  text-align: center;

  :deep(.ant-empty-description) {
    color: #666;
  }

  .ant-btn {
    margin-top: 16px;
  }
}

/* 购物车列表加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 0;
  text-align: center;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.loading-text {
  color: #666;
  font-size: 16px;
  margin-top: 10px;
}

.loading-button {
  margin-top: 10px;
}

/* 推荐列表加载状态样式 */
.skeleton-card {
  height: 100%;
  cursor: default;
}

.recommendation-image-skeleton {
  height: 240px;
  background-color: #f5f5f5;
  animation: skeleton-pulse 1.4s ease-in-out infinite;
  border-radius: 8px 8px 0 0;
}

.recommendation-meta-skeleton {
  padding: 12px;
}

.title-skeleton {
  height: 16px;
  width: 80%;
  background-color: #f5f5f5;
  animation: skeleton-pulse 1.4s ease-in-out infinite;
  margin-bottom: 8px;
  border-radius: 4px;
}

.price-skeleton {
  height: 14px;
  width: 50%;
  background-color: #f5f5f5;
  animation: skeleton-pulse 1.4s ease-in-out infinite;
  border-radius: 4px;
}

.rec-action-skeleton {
  height: 32px;
  margin: 12px;
  background-color: #f5f5f5;
  animation: skeleton-pulse 1.4s ease-in-out infinite;
  border-radius: 4px;
}
:deep(:where(.css-dev-only-do-not-override-12unj27).ant-btn-link) {
  color: #000;
}
:deep(:where(.css-dev-only-do-not-override-12unj27).ant-btn-link:hover) {
  color: #000;
}

@keyframes skeleton-pulse {
  0% {
    background-color: #f5f5f5;
  }
  50% {
    background-color: #ebebeb;
  }
  100% {
    background-color: #f5f5f5;
  }
}

/* 响应式布局 - 1280px断点 */
@media (max-width: 1280px) {
  .page-container {
    padding: 16px 0;
  }

  .cart-container {
    padding: 0 12px;
  }

  .cart-card {
    margin-top: 16px;
  }

  .recommendations {
    padding: 20px;
  }

  .recommendation-image {
    height: 180px;
  }

  /* 模态框响应式调整 */
  :deep(.checkout-modal .ant-modal) {
    max-width: 90%;
    margin: 0 auto;
  }

  :deep(.checkout-modal .ant-modal-content) {
    padding: 16px;
  }

  :deep(.checkout-modal .ant-modal-body) {
    padding: 16px 0;
  }
}

/* 响应式布局 - 768px断点 */
@media (max-width: 768px) {
  .page-container {
    padding: 12px 0;
  }

  .cart-container {
    padding: 0 8px;
  }

  .recommendations {
    padding: 16px;
    margin-top: 24px;
  }

  .recommendations h3 {
    margin-bottom: 16px;
    font-size: 16px;
  }

  .recommendation-image {
    height: 160px;
  }

  .rec-price {
    font-size: 14px;
  }

  /* 表格在小屏幕上的调整 */
  :deep(.cart-table .ant-table-thead > tr > th),
  :deep(.cart-table .ant-table-tbody > tr > td) {
    padding: 8px 4px;
  }

  :deep(.cart-table .ant-table-cell) {
    font-size: 12px;
  }

  /* 底部结算栏在小屏幕上的调整 */
  .cart-footer {
    flex-direction: column;
    gap: 12px;
  }

  .cart-footer-right {
    width: 100%;
    flex-direction: column;
    gap: 12px;
  }

  .cart-summary {
    width: 100%;
    text-align: center;
  }

  .total-price {
    margin-left: 0;
    margin-top: 8px;
    display: block;
  }
}

/* 响应式布局 - 576px断点 */
@media (max-width: 576px) {
  .recommendations {
    padding: 12px;
  }

  .recommendation-image {
    height: 140px;
  }

  /* 隐藏某些表格列 */
  :deep(.cart-table .ant-table-cell:nth-child(3)),
  :deep(.cart-table .ant-table-cell:nth-child(4)) {
    display: none;
  }
}
/* 骨架屏样式 */
.recommendation-image-skeleton {
  width: 100%;
  height: 240px;
}

:deep(.ant-skeleton-image) {
  width: 100%;
  height: 100%;
}

@media (max-width: 768px) {
  .recommendation-image-skeleton {
    height: 160px;
  }
}

@media (max-width: 576px) {
  .recommendation-image-skeleton {
    height: 140px;
  }
}
</style>
